<template>
	<!-- <h3>添加商品</h3> -->
	<div style="display: flex;align-items: center;margin-bottom: 10px;">
		<span style="margin-right: 10px;cursor: pointer;display: flex;align-items: center;" @click="back">
			<el-icon><ArrowLeft /></el-icon>
			<span>返回</span>
			<span style="margin-left: 10px;">|</span>
		</span>
		<h3>{{goodsItem ? "编辑商品" : "添加商品"}}</h3>
	</div>
	<!-- <span style="margin-right: 10px;cursor: pointer;" @click="back"><el-icon><ArrowLeft /></el-icon>返回</span> -->
	<el-menu  ellipsis
	    :default-active="activeIndex"
	    class="el-menu-demo"
	    mode="horizontal"
	    @select="handleSelect"
		style="margin-bottom: 10px;"
	  >
	    <el-menu-item index="1">基础信息</el-menu-item>
	    <el-menu-item index="2">价格库存</el-menu-item>
		<el-menu-item index="3">配送设置</el-menu-item>
		<el-menu-item index="4">商品详情</el-menu-item>
	</el-menu>
	<el-form :model="formData" label-width="auto" style="max-width: 100%;margin-left: 30px;">
		<div v-if="activeIndex === '1'">
			<el-form-item label="商品类型" prop="pageName">
				  <div 
				  style="border: 1px solid #959595;margin-right: 15px;height: 50px;width: 100px;" 
				  :class="{selectedStyle:selectedImage == 'img1'}"
				  @click="selectImage('img1','实物商品')"
				  >
					<h4 style="line-height: 25px;text-align: center;">实物商品</h4>
					<p style="line-height: 25px;text-align: center;">(物流发货)</p>
				  </div>
				  <div
				  style="border: 1px solid #959595;margin-right: 15px;height: 50px;width: 100px;" 
				  :class="{selectedStyle:selectedImage == 'img2'}"
				  @click="selectImage('img2','虚拟商品')"
				  >
					<h4 style="line-height: 25px;text-align: center;">虚拟商品</h4>
					<p style="line-height: 25px;text-align: center;">(无需物流)</p>
				  </div>
			</el-form-item>
			<el-form-item label="商品名称" prop="goodsName" required>
			  <el-input  v-model="formData.goodsName"
					placeholder="请输入商品名称"
					show-word-limit maxlength="60" style="width: 300px;"/>
			</el-form-item>
			<el-form-item label="副标题" prop="goodsAlias">
			  <el-input  v-model="formData.goodsAlias" placeholder="请输入副标题"
					show-word-limit maxlength="80" style="width: 300px;"/>
			</el-form-item>
			<el-form-item label="商品图片" prop="goodsImage" required>
			    <el-upload
					v-model="formData.goodsImage"
					  class="avatar-uploader"
					  :action="uploadUrl"
					  :show-file-list="false"
					  :on-success="handleAvatarSuccess"
					  :before-upload="beforeAvatarUpload"
					>
					  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
					  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
			    </el-upload>
			</el-form-item>
			<el-form-item label="商品分类" prop="separateId" required>
				<el-tree-select
				    v-model="formData.separateId"
				    :data="myOptions"
				    :render-after-expand="false"
					placeholder="请选择商品分类"
					check-strictly
					show-checkbox
				    style="width: 200px"
				  />
			    <!-- <el-select v-model="formData.separateId" placeholder="请选择商品分类" style="width: 200px;">
			        <el-option
			          v-for="item in myOptions"
					  
			          :key="item.separateId"
			          :label="item.separateName"
			          :value="item.separateId"
			          :disabled="item.disabled"
			        />
			    </el-select> -->
				<span style="margin: 0 10px;cursor: pointer;color: #4b5db9;" @click="reload">刷新</span>
				<span style="cursor: pointer;color: #4b5db9;" @click="router.push('/marketSys/goodsmanage/goodsclass')">添加分类</span>
			</el-form-item>
			<el-form-item label="品牌等级" prop="logoId">
			    <el-select v-model.number="formData.logoId" placeholder="请选择商品品牌" style="width: 200px;">
			        <el-option
			          v-for="item in props.myOptions1"
			          :key="item.logoId"
			          :label="item.logoName"
			          :value="item.logoId"
			          :disabled="item.disabled"
			        />
			    </el-select>
				<span style="margin: 0 10px;cursor: pointer;color: #4b5db9;" @click="reload">刷新</span>
				<span style="cursor: pointer;color: #4b5db9;" @click="router.push('/marketSys/goodsmanage/goodsbrand')">添加品牌</span>
			</el-form-item>
			<el-form-item label="商品标签" prop="tagId">
			    <el-checkbox-group v-model="formData.tagIds">
					<el-checkbox
					  v-for="item in props.myOptions2"
					  :key="item.tagId"
					  :label="item.tagName"
					  :value="item.tagId">
					</el-checkbox>
			    </el-checkbox-group>
				<span style="margin: 0 10px;cursor: pointer;color: #4b5db9;" @click="reload">刷新</span>
				<span style="cursor: pointer;color: #4b5db9;" @click="router.push('/marketSys/goodsmanage/goodstag')">添加商品标签</span>
			</el-form-item>
			<el-form-item label="商品服务" prop="goodsSend">
			    <el-radio-group v-model="formData.goodsSend">
					<!-- <el-radio :value="1">包邮</el-radio>
					<el-radio :value="2">不包邮</el-radio> -->
					<el-radio
					  v-for="item in myOptions3"
					  :key="item.serviceId"
					  :label="item.serviceName"
					  :value="item.serviceId">
					</el-radio>
			    </el-radio-group>
				<span style="margin: 0 10px;cursor: pointer; color: #4b5db9;" @click="reload">刷新</span>
				<span style="cursor: pointer; color: #4b5db9;" @click="router.push('/marketSys/goodsmanage/goodsservey')">添加商品服务</span>
			</el-form-item>
			<el-form-item label="商品状态" prop="goodsSell">
				<el-radio-group v-model="formData.goodsSell">
					<el-radio value="上架">上架</el-radio>
					<el-radio value="下架">下架</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="单位" prop="goodsUnit">
			  <el-input  v-model="formData.goodsUnit" placeholder="请输入单位,默认为:件"
					show-word-limit maxlength="6" style="width: 300px;"/>
			</el-form-item>
			<el-form-item label="虚拟销量" prop="goodsCheating">
				<div>
					<el-input  v-model.number="formData.goodsCheating" placeholder="请输入虚拟销量"
						show-word-limit maxlength="10" style="width: 300px;">
						<template #append>件</template>
					</el-input>
					<p style="color: #707070;font-size: 13px;">虚拟销量只在前台展示中参与计算</p>
				</div>
			</el-form-item>
		</div>
		<!-- 价格库存 -->
		<div v-if="activeIndex === '2'">
			<el-form-item label="规格类型" prop="specificationState">
			  <el-radio-group v-model="formData.specificationState">
			  	<el-radio :value="0">单规格</el-radio>
			  	<el-radio :value="1">多规格</el-radio>
			  </el-radio-group>
			</el-form-item>
			<div v-if="formData.specificationState==0">
				<el-form-item label="销售价" prop="priceValue"
					:rules="[
						{pattern:/^\d+(\.\d+)?$/, message: '请输入大于0的数字',trigger:'blur' },
					]"
				>
					<el-input type='text' v-model="formData.priceValue" placeholder="0.00" style="width: 300px;">
						<template #append>元</template>
					</el-input>
				</el-form-item>
				 <el-form-item label="划线价" prop="priceOriginal"
				:rules="[
					{pattern:/^\d+(\.\d+)?$/, message: '请输入大于0的数字',trigger:'blur' },
				]"
				>
					<el-input type='text'  v-model="formData.priceOriginal" placeholder="0.00" style="width: 300px;">
						<template #append>元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="成本价" prop="priceBasic"
				:rules="[
					{pattern:/^\d+(\.\d+)?$/, message: '请输入大于0的数字',trigger:'blur' },
				]"
				>
					<el-input type='text'  v-model="formData.priceBasic" placeholder="0.00" style="width: 300px;">
						<template #append>元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="重量" prop="priceWeight"
					:rules="[
						{pattern:/^\d+(\.\d+)?$/, message: '请输入大于0的数字',trigger:'blur' },
					]"
				>
					<el-input type='number'  v-model.number="formData.priceWeight" placeholder="0.000" style="width: 300px;">
						<template #append>kg</template>
					</el-input>
				</el-form-item>
				<el-form-item label="体积" prop="priceVolume"
					:rules="[
						{pattern:/^\d+(\.\d+)?$/, message: '请输入大于0的数字',trigger:'blur' },
					]"
				>
					<el-input  type='number' v-model.number="formData.priceVolume" placeholder="0.000" style="width: 300px;">
						<template #append>m³</template>
					</el-input>
				</el-form-item>
				<el-form-item label="商品库存" prop="priceNum"
					:rules="[
						{pattern:/^[1-9]\d*$/, message: '请输入大于0的整数',trigger:'blur' },
					]"
				>
					<el-input  type='number' v-model.number="formData.priceNum" placeholder="0.000" style="width: 300px;">
						<template #append>件</template>
					</el-input>
				</el-form-item>
				<el-form-item label="商品编码" prop="priceCode">
					<el-input  v-model="formData.priceCode" style="width: 300px;"placeholder="请输入商品编码" />
				</el-form-item>
			</div>
			<div v-else-if="formData.specificationState==1">
				<el-form-item label="商品规格">
					<div v-for="(component, index) in components" :key="index" style="width: 93%;">
						<!-- <MyDiv></MyDiv> -->
					
						<div style="width: 100%;background-color: #f7f7f7;height: 110px;padding: 20px;margin-bottom: 15px;">
							<el-input style="width: 250px;" v-model="components[index]" placeholder="请输入规格项,如颜色/尺码/大小" />
							<div class="goodsQuality">
								<div class="qualityBox"></div>
								<div v-for="(mycomponent, typeIndex) in mycomponents[index]">
									<el-input v-model="mycomponents[index][typeIndex]" style="width: 200px;height: 30px;margin-top: 25px;margin-right: 20px;" placeholder="请输入规格值,如白色" />
								</div>
							</div>
							<p @click="addMyComponent(index)" style="cursor: pointer;width: 100px;">+添加规格值</p>
						</div>
					</div>
				</el-form-item>
				<el-form-item>
				  <el-button type="primary" @click="addComponent">添加规格</el-button>
				  <el-button  @click="confirmAdd">确认添加</el-button>
				</el-form-item>
				<div>
					<span style="font-size: 15px;">批量设置</span>
					<el-tree-select
					    v-model="selectedValue"
					    :data="setData"
						:render-after-expand="false"
						show-checkbox
						check-strictly
						placeholder="请选择规格"
					    style="width: 200px;margin: 0 4px;"
					  />
					<el-input v-model.number="oneP" style="width: 90px;margin: 0 4px;"  placeholder="销售价"/>
					<el-input v-model.number="twoP" style="width: 90px;margin: 0 4px;"  placeholder="划线价"/>
					<el-input v-model.number="threeP" style="width: 90px;margin: 0 4px;"  placeholder="成本价"/>
					<el-input v-model.number="fourP" style="width: 90px;margin: 0 4px;"  placeholder="库存"/>
					<el-input v-model.number="fiveP" style="width: 90px;margin: 0 4px;"  placeholder="重量(kg)"/>
					<el-input v-model.number="sixP" style="width: 90px;margin: 0 4px;"  placeholder="体积(m³)"/>
					<el-input v-model.number="sevenP" style="width: 90px;margin: 0 4px;"  placeholder="商品编码"/>
					<el-button type="primary" @click="getSelected">确定</el-button>
				</div>
				<el-table style="width: 100%" :data="dataArr" 
					:span-method="objectSpanMethod"
					v-if="showTable"
				>
				    <el-table-column prop="specificationOne"  :label="goodsItem ? titleArr[0] : components[0]"/>
					<el-table-column v-if="showSecond" prop="specificationTwo" :label="goodsItem ? titleArr[1] : components[1]"/>
					<el-table-column v-if="showThird" prop="specificationThree" :label="goodsItem ? titleArr[2] : components[2]"/>
				    <el-table-column label="图片">
						<template #default = "scope">
							<!-- <div class="goodsDetail"> -->
								<el-upload
									v-model="scope.row.goodsImage"
									  class="avatar-uploader addimg"
									  :action="uploadUrl"
									  :show-file-list="false"
									 
									  :on-success="function (res, file) { return handleAvatarSuccess2(res, file, scope.$index)}"
									  :before-upload="beforeAvatarUpload"
									>
									
									  <!-- <img v-if="imageUrl" :src='imageUrl' class="avatar" /> -->
									 <img v-if="scope.row.showImg" :src='scope.row.showImg' class="avatar" />
									 <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
								</el-upload>
								<!-- <img :src="downloadUrl+image.row.goodsImage" style=" width:50px;height: 50px;object-fit: cover;"> -->
							<!-- </div> -->
						</template>
					</el-table-column>
					<el-table-column  label="销售价" prop="priceValue">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceValue" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column  label="划线价">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceOriginal" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column   label="成本价">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceBasic" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column label="库存">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceNum" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column  label="重量(kg)">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceWeight" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column label="体积(m³)">
						<template #default="scope">
							<el-input style="width: 80px" v-model.number="scope.row.priceVolume" placeholder="0.00"/>
						</template>
					</el-table-column>
					<el-table-column label="商品编码">
						<template #default="scope">
							<el-input style="width: 80px" v-model="scope.row.priceCode" />
						</template>
					</el-table-column>
					<el-table-column  label="默认规格">
						<template #default="scope">
							<el-switch v-model="scope.row.delFlag"/>
						</template>
						
					</el-table-column>
				</el-table>
			</div>
		</div>
		<div v-if="activeIndex === '3'">
			<el-form-item label="配送方式" prop="goodsDelivery" required>
			  <el-radio-group v-model="formData.goodsDelivery">
			  	<el-radio value="物流配送">物流配送</el-radio>
			  	<el-radio value="同城配送">同城配送</el-radio>
				<el-radio value="门店自提">门店自提</el-radio>
			  </el-radio-group>
			</el-form-item>
		</div>
		<div v-if="activeIndex === '4'">
			<el-form-item label="商品详情" required>
				<div style="border: 1px solid #ccc">
				      <Toolbar
				        style="border-bottom: 1px solid #ccc"
				        :editor="editorRef"
				        :defaultConfig="toolbarConfig"
				        :mode="mode"
				      />
				      <Editor
				        style="height: 500px; overflow-y: hidden;"
				        v-model="valueHtml"
				        :defaultConfig="editorConfig"
				        :mode="mode"
				        @onCreated="handleCreated"
				      />
				    </div>
			</el-form-item>
		</div>
		<el-form-item>
		  <el-button type="primary" @click="save">保存</el-button>
		  <el-button>返回</el-button>
		</el-form-item>
	</el-form>
	
</template>

<script setup>
	import {ref,reactive,onMounted,onBeforeUnmount, shallowRef,defineEmits} from "vue"
	import {GoodServiceCase,UpdateGoods,InsertGoods,GoodsDetail} from "@/api"
	import {useRoute,useRouter} from "vue-router";
	import {Plus,ArrowLeft} from '@element-plus/icons-vue'
	import {uploadUrl,baseUrl,downloadUrl} from "@/utils/request";
	import {defineProps} from "vue"
	import '@wangeditor/editor/dist/css/style.css' 
	import {DomEditor} from '@wangeditor/editor'
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	let route = useRoute();
	let router = useRouter()
	let goodsItem = sessionStorage.getItem("itemGoods")
	
	const props=defineProps(['myOptions1','myOptions','myOptions2','aIndex'])
	// console.log(props.myOptions2[1].tagId)

	// 富文本编辑框
	let mode="default"
	const editorRef = shallowRef()
	// const valueHtml = ref('<p>hello</p>')
	onMounted(() => {
		// console.log("editorRef",editorRef)
	})
	const toolbarConfig = {}
	const editorConfig = {
			MENU_CONF: {},
		}
	editorConfig.placeholder ='请输入内容...'
	editorConfig.MENU_CONF['color'] = {
			colors: ['#000', '#333', '#666']
	}
	editorConfig.MENU_CONF['uploadImage'] = {
		server: uploadUrl,
		fieldName: "file",
		headers: {
			Authorization:sessionStorage.getItem("token")
		},
		onSuccess(file, res) {
			// console.log(`${file.name} 上传成功`, res)
		},
		onFailed(file, res) { // JS 语法
			// console.log(`${file.name} 上传失败`, res)
			const editor = editorRef.value
			if(res.code==200){
				editor.dangerouslyInsertHtml(`<img src='${downloadUrl+res.data}'>`)
			}
		},
		// 上传错误，或者触发 timeout 超时
		onError(file, err, res) { // JS 语法
			// console.log(`${file.name} 上传出错`, err, res)
		},
	}
	// 组件销毁时，也及时销毁编辑器

	onBeforeUnmount(() => {
		const editor = editorRef.value
		if (editor == null) return
		editor.destroy()
	})
	const handleCreated = (editor) => {
		editorRef.value = editor
		// console.log(editorRef.value,'ddddd')
		editorRef.value.setHtml(formData.goodsDetails)
	}

	
	
	// 多规格添加新div	规格名
	const components = ref([null]); // 初始化一个空数组来存储子  
	const addComponent = () => {  
		//console.log(components.value.length)
		if(components.value.length>2){
			ElMessage({
			    message:"最多只能添加三个规格",
			    type: 'warning',
			})
		}else{
			const newArr=[""]
			mycomponents.value.push(newArr);
			components.value.push(null); 
		}
	};
	// 多规格添加新input	规格值
	const mycomponents = ref([
		[null],
	]); // 初始化一个空数组来存储  
	const addMyComponent = (num) => {
		mycomponents.value[num].push(null);
	};
	// 点击确认添加
	let first = [];
	let second = [];
	let third = [];
	let showTable = ref(false)
	let dataArr=ref([]);
	let showSecond=ref(false);
	let showThird=ref(false);
	let target = ref(false)

	// 批量设置下拉框
	let setData =ref([])
	const confirmAdd=()=>{
		first = [];
		second = [];
		third = [];
		first=mycomponents.value[0];
		second=mycomponents.value[1];
		third=mycomponents.value[2];
		// console.log("components",components.value,"first",first,"second",second,"third",third)
		// console.log("mycomponents",mycomponents.value)
		if(first!=""){
			composeFn()
		}else{
			ElMessage({
			    message:"请输入商品规格",
			    type: 'warning',
			})
		}
		showTable.value=true
		allSelect(first,second,third)
		// console.log("setData",setData);
	}
	
	// 批量设置下拉
	const allSelect=(first,second,third)=>{
		// console.log(first,second,third)
		for(var i=0;i<first.length;i++){
			var firstObj = {
				value:first[i],
				label:first[i],
				children:[]
			}
			if(second != undefined){
				for(var j=0;j<second.length;j++){
					var secondObj = {
						value:first[i]+"-"+second[j],
						label:second[j],
						children:[]
					}
					if(third != undefined){
						for(var m=0;m<third.length;m++){
							var thirdObj = {
								value:first[i]+"-"+second[j]+"-"+third[m],
								label:third[m],
								children:[]
							}
							secondObj.children.push(thirdObj)
						}
					}
					firstObj.children.push(secondObj)
				}
			}
			setData.value.push(firstObj)
			// console.log(setData.value)
		}
	}
	
	const selectedValue = ref(null); // 用于存储选中的值
	// 批量设置中的值
	let oneP = ref("");
	let twoP = ref("");
	let threeP = ref("");
	let fourP = ref("");
	let fiveP = ref("");
	let sixP = ref("");
	let sevenP = ref("");
	const getSelected=()=>{
		// console.log("选中的值",selectedValue.value)
		var words = selectedValue.value.split("-")
		// console.log(words,dataArr.value)
		dataArr.value.forEach(x=>{
			if(words.length==1){
				if(x.specificationOne==words[0]){
					x.priceValue = oneP.value;
					x.priceOriginal = twoP.value;
					x.priceBasic = threeP.value;
					x.priceNum = fourP.value;
					x.priceVolume = fiveP.value;
					x.priceWeight = sixP.value;
					x.priceCode = sevenP.value;
				}
			}else if(words.length==2){
				if(x.specificationOne==words[0] && x.specificationTwo==words[1]){
					x.priceValue = oneP.value;
					x.priceOriginal = twoP.value;
					x.priceBasic = threeP.value;
					x.priceWeight = fourP.value;
					x.priceVolume = fiveP.value;
					x.priceNum = sixP.value;
					x.priceCode = sevenP.value;
				}
			}else if(words.length==3){
				if(x.specificationOne==words[0] && x.specificationTwo==words[1] && x.specificationThree==words[2]){
					x.priceValue = oneP.value;
					x.priceOriginal = twoP.value;
					x.priceBasic = threeP.value;
					x.priceWeight = fourP.value;
					x.priceVolume = fiveP.value;
					x.priceNum = sixP.value;
					x.priceCode = sevenP.value;
				}
			}
		})
		// console.log("dataArr",dataArr.value)
	}
	
	const composeFn=()=>{
		first.forEach(v1=>{
				if(second){
					second.forEach(v2=>{
						showSecond.value=true
						if(third){
							showThird.value=true
							third.forEach(v3=>{
								let obj={
									specificationOne:v1,
									specificationTwo:v2,
									specificationThree:v3,
									goodsImage: "",
									priceValue: "",
									priceOriginal: "",
									priceBasic: "",
									priceWeight: "",
									priceVolume: "",
									priceNum: "",
									priceCode: "",
									delFlag: false,
								}
								dataArr.value.push(obj)
							})
						}else{
							let obj={
								specificationOne:v1,
								specificationTwo:v2,
								specificationThree:"",
								goodsImage: "",
								priceValue: "",
								priceOriginal: "",
								priceBasic: "",
								priceNum: "",
								priceWeight: "",
								priceVolume: "",
								priceCode: "",
								delFlag: false,
								showImg:""
		
							}
							dataArr.value.push(obj)
						}
						
					})
				}else{
					let obj={
						specificationOne:v1,
						specificationTwo:"",
						specificationThree:"",
						goodsImage: "",
						priceValue: "",
						priceOriginal: "",
						priceBasic: "",
						priceNum: "",
						priceWeight: "",
						priceVolume: "",
						priceCode: "",
						delFlag: false,
						showImg:""
						
					}
					dataArr.value.push(obj)
				}
			})
			// console.log('data...',dataArr.value)
		
	}

	// 合并单元格
	const objectSpanMethod = ({
		row,
		column,
		rowIndex,
		columnIndex,
		}) => {
			//console.log(row)
			if(columnIndex==0 && second != undefined){
				if(second.length>1 || third.length>1){
					if(rowIndex%(dataArr.value.length/first.length)==0){
						return{
							rowspan: (dataArr.value.length/first.length),
							colspan: 1,
						}
					}else{
						return{
							rowspan: 0,
							colspan: 0,
						}
					}
				}
			}
			if(columnIndex==1 && third !== undefined){
				if(third.length>1 ){
					if(rowIndex%(third.length)==0){
						return{
							rowspan: third.length,
							colspan: 1,
						}
						
					}else{
						return{
							rowspan: 0,
							colspan: 0,
						}
					}
				}
			}
		}


	const activeIndex = ref('1');
	function handleSelect(index) {
	  activeIndex.value = index;
	}
	
	let chooseOne = ref("实物商品")
	
	let formData = reactive({
		siteId:1,
		goodsVirtual:chooseOne.value,
		goodsName:"",
		goodsAlias:"",
		goodsImage:"",
		separateId:"",
		logoId:"",
		tagIds:[],
		goodsSend:1,
		goodsSell:"上架",
		goodsUnit:"",
		goodsCheating:"",
		specificationState:0,
		priceValue:"",
		priceOriginal:"",
		priceBasic:"",
		priceWeight:"",
		priceVolume:"",
		priceNum:"",
		priceCode:"",
		goodsDelivery:"物流配送",
		goodsState:"销售中",
		specification:dataArr.value,
		goodsDetails:"",
	})
	
	// 点击保存
	const save=async()=>{
		const editor = editorRef.value
		formData.goodsDetails = editor.getHtml()
		// console.log(editorCont)
		// formData.goodsDetails=editorCont
		// 多规格中的开关
		if(formData.specificationState==0){
			formData.specification=[]
		}else{
			if(formData.specification.length !=0){
				formData.specification.forEach(item=>{
					if(item.delFlag == false){
						item.delFlag=1
					}else if(item.delFlag == true){
						item.delFlag=0
					}
				})
			}
		}
		
		if(goodsItem){
			// 修改
			// console.log("修改前formData",formData)
			let res = await UpdateGoods(formData)
			// console.log("修改商品",res)
			if(res != undefined){
				ElMessage.success(res)
			}
		}else{
			let res = await InsertGoods(formData)
			// console.log("添加结果",res)
			if(res != undefined){
				ElMessage.success(res)
			}
		}
		emit('update-message',acIndex);
		// console.log("editorCont",editorCont)
		// console.log("这是formdata:",formData)
	}
	
	
	// 点击图片
	let selectedImage=ref("img1");
	const selectImage=(imgId,chooseone)=>{
		chooseOne.value=chooseone
		selectedImage.value=imgId;
		// console.log(chooseOne.value,selectedImage.value)
	}
	
	//图片上传
	const imageUrl = ref('')
	const handleAvatarSuccess= (response,uploadFile) => {
		//console.log('上传成功',response)
		imageUrl.value = URL.createObjectURL(uploadFile.raw)
		//imageUrl.value=baseUrl+"manager/"+response.data
		formData.goodsImage=response.data
	}
	
	const handleAvatarSuccess2= (response,uploadFile,index) => {
		//console.log('上传成功',response)
		//imageUrl.value = URL.createObjectURL(uploadFile.raw)
		//imageUrl.value=baseUrl+"manager/"+response.data
		//formData.goodsImage=response.data
		
		dataArr.value[index].showImg=URL.createObjectURL(uploadFile.raw)
		dataArr.value[index].goodsImage=response.data
	}
	const beforeAvatarUpload= (rawFile) => {
		//console.log(rawFile)
		let reg=/(jpg|png|jpeg)$/
	    if (!reg.test(rawFile.type)) {
	    ElMessage.error('图片只能是jpg/jpeg/png格式的')
	    return false
	    } else if (rawFile.size / 1024 / 1024 > 4) {
			ElMessage.error('图片的大小不能超过4MB')
			return false
	    }
	  return true
	}
	
	let myOptions3=ref([])
	// 商品服务下拉框
	const goodsService=async ()=>{
		let res=await GoodServiceCase(1)
		myOptions3.value=res
		//console.log("商品服务",res,myOptions3.value)
	}
	
	// 去商品分类
	const goGoodsClass=()=>{
		router.push("/marketSys/goodsmanage/goodsclass")
	}
	
	// 点击刷新
	const reload=()=>{
		window.location.reload()
	}
	
	// 点击返回
	const emit = defineEmits(['update-message']);
	let acIndex=props.aIndex
	const back=()=>{
		emit('update-message',acIndex);
		// console.log(acIndex)
	}

	// 编辑商品 表格头部label
	let titleArr=ref([])
	let formObj=reactive({});
	onMounted(async()=>{
		goodsService()
		if(goodsItem){
			// goodsId
			Object.assign(formObj,JSON.parse(goodsItem))
			// console.log("编辑商品",formObj)
			let res=await GoodsDetail({
				siteId:1,
				goodsId:formObj.goodsId
			})
			// console.log("商品详情",res)
			Object.assign(formData,res.goodsInfo)
			// formData=res
			formData.separateId=Number(formData.separateId)
			formData.logoId=Number(formData.logoId)
			imageUrl.value=downloadUrl+formData.goodsImage
			// editorRef.value=formData.goodsDetails
			console.log("editorRef",editorRef)
			// editorRef.value.insertHtml(formData.goodsDetails)
			

			if(formData.tagIds== null){
				formData.tagIds=[]
			}
			// //  编辑回显商品多规格
			if(formData.specification.length != 0){
				showTable.value=true
				dataArr.value = formData.specification
				formData.specificationState=1
				// 批量设置下拉
				let selectArr = formData.specification
				// 表格表头
				titleArr.value.push("规格1")
				if(selectArr[0].specificationTwo != ""){
					titleArr.value.push("规格2")
					showSecond.value=true
					if(selectArr[0].specificationThree != ""){
						titleArr.value.push("规格3")
						showThird.value=true
					}
				}
				// console.log('selectArr',selectArr)
				// 批量设置下拉
				let first=[];
				let second=[]
				let third=[]
				for(var i=0;i<selectArr.length;i++){
					first.push(selectArr[i].specificationOne)
					if(selectArr[i].specificationTwo != ""){
						second.push(selectArr[i].specificationTwo)
						if(selectArr[i].specificationThree){
							third.push(selectArr[i].specificationThree)
						}
					}
				}
				first=Array.from(new Set(first));
				second=Array.from(new Set(second));
				third=Array.from(new Set(third));
				if(second.length==0){
					second=undefined
					third=undefined
				}else if(third.length==0){
					third=undefined
				}
				// console.log(first,second,third)
				allSelect(first,second,third)
				console.log("setData",setData)
			}else{
				formData.specificationState=0
			}
			// console.log("formData",formData)
			// console.log("dataArr",dataArr.value)
		}
	})
</script>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>

<style lang="less">
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 100px;
		height: 100px;
	}
	// .avatar-uploader{
	// 	width: 40px;
	// 	height: 50px;
	// }
	.addimg{
		width: 40px;
		height: 50px;
		.el-upload{
			width: 60px;
			height: 60px;
		}
	}
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		text-align: center;
	}

	.el-menu-item {
		margin-right:20px !important;
	}
	.el-menu-item.is-active{
		background-color: #fff !important;
	}
	.selectedStyle{
		border: 1px solid blue !important;
	}
	
	.goodsQuality{
		display: flex;
		margin-left: 20px;
		height: 55px;
		flex-wrap: wrap;
		.qualityBox{
			width: 20px;
			height: 40px;
			border-left: 1px solid #ccc;
			border-bottom: 1px solid #ccc;
		}
	}
</style>
